<template>
  <view class="container">
    <canvas canvas-id="canvas" @touchstart="startBall"></canvas>
  </view>
</template>

<script>
export default {
  data() {
    return {
      ball: {
        x: 50,
        y: 50,
        vx: 2,
        vy: 2,
        radius: 10
      },
      requestId: null
    };
  },
  methods: {
    drawBall(ctx) {
      ctx.beginPath();
      ctx.arc(this.ball.x, this.ball.y, this.ball.radius, 0, Math.PI * 2);
      ctx.fillStyle = "#FF0000";
      ctx.fill();
      ctx.closePath();
    },
    updateBall() {
      const canvasWidth = uni.getSystemInfoSync().windowWidth;
      const canvasHeight = uni.getSystemInfoSync().windowHeight; // Adjust as per canvas size
      
      // Check for wall collisions
      if (this.ball.x + this.ball.vx > canvasWidth - this.ball.radius || this.ball.x + this.ball.vx < this.ball.radius) {
        this.ball.vx = -this.ball.vx;
      }
      if (this.ball.y + this.ball.vy > canvasHeight - this.ball.radius || this.ball.y + this.ball.vy < this.ball.radius) {
        this.ball.vy = -this.ball.vy;
      }
      
      // Update ball position
      this.ball.x += this.ball.vx;
      this.ball.y += this.ball.vy;
    },
    startBall() {
      const ctx = uni.createCanvasContext('canvas', this);
      const loop = () => {
        ctx.clearRect(0, 0, uni.getSystemInfoSync().windowWidth, uni.getSystemInfoSync().windowHeight);
        this.drawBall(ctx);
        this.updateBall();
        ctx.draw();
        this.requestId = requestAnimationFrame(loop);
      };
      loop();
    },
    stopBall() {
      if (this.requestId) {
        cancelAnimationFrame(this.requestId);
      }
    }
  },
  onUnload() {
    this.stopBall();
  }
};
</script>

<style>
.container {
  width: 100%;
  height: 100vh;
}
canvas{
	width: 100%;
	height: 100vh;
}
</style>
